package com.zlyx.easy.security.authentication.token;

import java.util.Collection;
import java.util.Map;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * <p>
 * 授权token
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
public class AuthenticationToken extends AbstractAuthenticationToken {

	private static final GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();

	private static final long serialVersionUID = 1L;

	/**
	 * 用户唯一标识
	 */
	protected Object principal;

	/**
	 * 授权类型
	 */
	protected String grantType;

	/**
	 * 客户端id
	 */
	protected String clientId;

	/**
	 * 请求参数
	 */
	protected Map<String, String[]> params;

	public AuthenticationToken(Object principal, String grantType, String clientId) {
		super(null);
		this.principal = principal;
		this.grantType = grantType;
		this.clientId = clientId;
		setAuthenticated(false);
	}

	public AuthenticationToken(Object principal, String clientId, Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.principal = principal;
		this.grantType = null;
		this.clientId = clientId;
		super.setAuthenticated(true);
	}

	public AuthenticationToken(UserDetails userDetails, String clientId) {
		super(authoritiesMapper.mapAuthorities(userDetails.getAuthorities()));
		this.principal = userDetails;
		this.grantType = null;
		this.clientId = clientId;
		super.setAuthenticated(true);
	}

	@Override
	public Object getCredentials() {
		return null;
	}

	/**
	 * @return the params
	 */
	public Map<String, String[]> getParams() {
		return params;
	}

	/**
	 * @param params the params to set
	 */
	public void setParams(Map<String, String[]> params) {
		this.params = params;
	}

	/**
	 * @return the principal
	 */
	public Object getPrincipal() {
		return principal;
	}

	/**
	 * @return the grantType
	 */
	public String getGrantType() {
		return grantType;
	}

	/**
	 * @return the clientId
	 */
	public String getClientId() {
		return clientId;
	}

	/**
	 * 查询参数
	 *
	 * @param name
	 * @return
	 */
	public String getParameter(String name) {
		return params == null || params.get(name) == null ? null : params.get(name)[0];
	}

	@Override
	public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
		if (isAuthenticated) {
			throw new IllegalArgumentException("not support");
		}
		super.setAuthenticated(false);
	}

	@Override
	public void eraseCredentials() {
		super.eraseCredentials();
	}

}
